package kotlinx.coroutines.script.tes

import android.os.Build
import zx.tas.model.ActivateRequest
import zx.tas.model.ApiResult
import zx.tas.model.CKV2Info
import zx.tas.model.HeartbeatRequest
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.POST
import java.io.File
import java.util.concurrent.TimeUnit


interface ApiServer {
    @POST("c/a")
    suspend fun activate(
        @Body request: ActivateRequest // 使用 Body 注解替代 FormUrlEncoded
    ): ApiResult<CKV2Info?>

    @POST("c/h")
    suspend fun heartbeat(
        @Body request: HeartbeatRequest // 使用 Body 注解
    ): ApiResult<String?>
}

val api: ApiServer by lazy { retrofit.create(ApiServer::class.java) }
private const val apiRouting = "https://huganya.com/" // 加密域名
var apiRequestingTime = 0L

private val retrofit: Retrofit
    get() {
        val loggingInterceptor = HttpLoggingInterceptor { printLog { it } }
        loggingInterceptor.level = if (isDebug) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE

        val headerInterceptor = Interceptor { chain ->
            apiRequestingTime = System.currentTimeMillis()
            val requestTime = apiRequestingTime.toString()
            val request = chain.request()
                .newBuilder()
                .header("Content-Type", "application/json; charset=utf-8")
                .addHeader("Connection", "close")
                .addHeader("r", "imm")
                .addHeader("bt", appBuildTime.toString())
                .addHeader("b", Build.BRAND)
                .addHeader("m", Build.MODEL)
                .addHeader("osv", Build.VERSION.SDK_INT.toString())
                .addHeader("vn", appVersionName)
                .addHeader("w", phoneDefaultDisplayPoint.x.toString())
                .addHeader("h", phoneDefaultDisplayPoint.y.toString())
                .addHeader("dpi", phoneDensityDpi.toString())
                .addHeader("t", requestTime)
                .addHeader("a", "s$appDeviceId$requestTime".md5)
                .build()
            chain.proceed(request)
        }
//        val trustManager = @SuppressLint("CustomX509TrustManager")
//        object : X509TrustManager {
//            override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) =
//                Unit
//
//            override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) =
//                Unit
//
//            override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
//        }
//        val sslContext = SSLContext.getInstance("TLS")
//        sslContext.init(null, arrayOf(trustManager), null)
//        val sslSocketFactory = sslContext.socketFactory
        fun filesDir(child: String) = File(appContext.filesDir, child).also { it.mkdirs() }
        val timeout = 5000L
        val builder = OkHttpClient.Builder()
//            .sslSocketFactory(sslSocketFactory, trustManager)
//            .hostnameVerifier { _, _ -> true }
            .addInterceptor(loggingInterceptor)
            .addInterceptor(headerInterceptor)
            .retryOnConnectionFailure(false)
            .connectTimeout(timeout, TimeUnit.MILLISECONDS)
            .readTimeout(timeout, TimeUnit.MILLISECONDS)
            .writeTimeout(timeout, TimeUnit.MILLISECONDS)
            .cache(Cache(filesDir("httpCache"), 52428800L)) // 50 * 1024 * 1024
        val client = builder.build()

        return Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(apiRouting)
            .client(client)
            .build()
    }


